import React, { useState, useRef, useEffect } from "react";

import { Icon, Progress } from "zarm";
import * as echarts from "echarts";
import s from "./style.module.less";
import cx from "classnames";
import dayjs from "dayjs";
import CustomIcon from "@/components/CustomIcon";
import { get, typeMap } from "@/utils";
import PopupDate from "@/components/PopupDate";

let proportionChart = null;

const Data = () => {
  const [type, setType] = useState("expense"); //图表类型
  const [currentMonth, setCurrentMonth] = useState(dayjs().format("YYYY-MM")); //显示时间
  const [totalExpense, setTotalExpense] = useState(0); //总支出
  const [totalIncome, setTotalIncome] = useState(0); //总收入
  const [total, setTotal] = useState(""); //总支出 或者 总收入
  const [meanExpense, setmeanExpense] = useState(""); //总收入平均值
  const [meanIncome, setmeanIncome] = useState(""); //总支出平均值
  const [expenseData, setExpenseData] = useState([]); //存储支出类型的数据
  const [incomeData, setIncomeData] = useState([]); //存储收入类型的数据
  const [sumDate, setSumDate] = useState(""); //总天数
  const [timeData, setTimeData] = useState([]);
  const monthRef = useRef();

  useEffect(() => {
    getData();
    return () => {
      proportionChart.dispose();
    };
  }, [currentMonth]);

  useEffect(() => {
    // 绘制折线图
    const theOpition = getTheOpiton(timeData, sumDate)
    setChart(theOpition);
    return () => {
      proportionChart.dispose();
    };
  }, [type]);

  // 初始化
  const getData = async () => {
    const { data } = await get(`/api/bill/data?date=${currentMonth}`);

    console.log("我要看看返回了什么", data);
    // 总收支
    setTotalExpense(data.total_expense);
    setTotalIncome(data.total_income);
    // 设置平均值
    setmeanExpense(data.total_expense_mean);
    setmeanIncome(data.total_income_mean);
    setSumDate(data.sumDate);
    setTimeData(data.time_data);

    // 处理好数据，返回一个折线图所需的opition
    const getNextOption = getTheOpiton(data.time_data, data.sumDate);

    // 过滤支出和收入
    const expense_data = data.total_data
      .filter((item) => item.pay_type == 1)
      .sort((a, b) => b.number - a.number); // 过滤出账单类型为支出的项
    const income_data = data.total_data
      .filter((item) => item.pay_type == 2)
      .sort((a, b) => b.number - a.number); // 过滤出账单类型为收入的项
    setExpenseData(expense_data);
    setIncomeData(income_data);
    console.log("查看请求到的总支出和总收入", totalExpense, totalIncome);

    // 绘制折线图
    setChart(getNextOption);
  };

  // 月份弹窗开关
  const monthShow = () => {
    monthRef.current && monthRef.current.show();
  };

  const selectMonth = (item) => {
    setCurrentMonth(item);
  };

  // 下面的一些需要的变量
  const showName = type == "expense" ? "支出" : "收入";
  const showColor = type == "expense" ? "#007fff" : "rgb(236, 190, 37)";
  const showData = `展示这<br/>个`;
  const showTitle = type == "expense" ? "支出分布" : "收入分布";

  // 获取到折线图所需的opition
  const getTheOpiton = (time_data, sumDate) => {
    let n = type == "expense" ? 1 : 2;
    // 先做x轴，为日期分布，由本月天数得到
    let xNumber = Array.from(new Array(sumDate));
    xNumber.forEach((item, index) => {
      xNumber[index] = index + 1;
    });

    // 再准备好一个数值组，用于对应真正那天花费
    let yNumber = Array.from(new Array(sumDate));
    yNumber.forEach((item, index) => {
      yNumber[index] = 0;
    });
    time_data.forEach((item) => {
      // 对当天数据进行总和,从而获取一个结点值
      yNumber[item.date - 1] = item.show.reduce((acc, cur) => {
        // 如果满足类别
        if (cur.pay_type == n) {
          acc += cur.number;
        }
        return acc;
      }, 0);
    });

    // 再准备一下点击结点的展示字符串       等等，01-12-19:00
    // const showMsg = `完成${1}次交易`

    // 准备好 opiton
    const theOpition = {
      xAxis: {
        type: "category",
        data: xNumber,
      },
      yAxis: {
        type: "value",
      },
      // 数据集
      series: [
        {
          name: showName,
          data: yNumber,
          type: "line",
          // 线条颜色
          lineStyle: {
            color: showColor,
          },
          // 点的颜色
          itemStyle: {
            color: showColor,
          },
        },
      ],

      title: {
        text: showTitle,
        left: "center",
      },
      tooltip: {
        trigger: "item",
        // formatter: showData, 
        formatter:`第{b}天<br/>该天累计消费{c}元 `,   //a  name     b   x轴    c  y轴
      },
    };

    // 将这个options 返回
    return theOpition;
  };

  // 绘制折线图
  const setChart = (data) => {
    if (window.echarts) {
      proportionChart = echarts.init(document.getElementById("echarts"));
      proportionChart.setOption({ ...data });

      // 这里备注 点击数值出现效果 的函数，后续可能用这个
      // proportionChart.getZr().on("click",function(param){}
      proportionChart.on("click", function (param) {
        console.log("这里是图标内的点击事件", param);
      });

      // 可能出现点击一次打印两次问题？？？我还没遇到，试试这个api的效果
      // 好吧。他的效果是关闭点击
      // proportionChart.off('click')

      // 想要提示框
      // proportionChart.dispatchAction({
      //   type: "showTip", //显示提示框，指定在相对容器的位置处显示提示框，如果指定的位置无法显示则无效。
      //   x: param.name, // 屏幕上的 x 坐标
      //   y: param.data, // 屏幕上的 y 坐标
      //   // 本次显示 tooltip 的位置。只在本次 action 中生效。
      //   // 缺省则使用 option 中定义的 tooltip 位置。
      //   // position: Array.<number>|string|Function
      // });
    }
  };
  return (
    <div className={s.data}>
      <div className={s.total}>
        {/* 时间 */}
        <div className={s.time} onClick={monthShow}>
          <span>{currentMonth}</span>
          <Icon className={s.date} type="date" />
        </div>
        <div className={s.type}>
          {/*支出 类别 */}
          <div
            onClick={() => setType("expense")}
            className={cx({
              [s.payTypeExpense]: true,
              [s.active]: type == "expense",
            })}
          >
            支出
          </div>
          {/*收入 类别 */}
          <div
            onClick={() => setType("income")}
            className={cx({
              [s.payTypeIncome]: true,
              [s.active]: type == "income",
            })}
          >
            收入
          </div>
        </div>

        {/* 数据展示 */}
        <div
          className={cx({
            [s.title]: true,
            [s.expense]: type == "expense",
            [s.income]: type == "income",
          })}
        >
          {type == "expense" ? "共支出" : "共收入"}
        </div>
        <div
          className={cx({
            [s.totalNumber]: true,
            [s.expense]: type == "expense",
            [s.income]: type == "income",
          })}
        >
          ¥{type == "expense" ? totalExpense : totalIncome}
        </div>
        <div className={s.meanNumber}>
          平均值¥{type == "expense" ? meanExpense : meanIncome}
        </div>
      </div>

      {/* 这里是折线图展示 */}
      <div id="echarts" className={s.echarts}></div>

      {/* 数据展示 */}
      <div className={s.content}>
        {(type == "expense" ? expenseData : incomeData).map((item) => (
          <div key={item.type_id} className={s.item}>
            <div className={s.left}>
              <div className={s.type}>
                <span
                  className={cx({
                    [s.expense]: type == "expense",
                    [s.income]: type == "income",
                  })}
                >
                  <CustomIcon
                    type={item.type_id ? typeMap[item.type_id].icon : 1}
                  />
                </span>
                <span className={s.name}>{item.type_name}</span>
              </div>
              <div className={s.progress}>
                ¥{Number(item.number).toFixed(2) || 0}
              </div>
            </div>
            {/* 这里是条形可视化区域 */}
            <div className={s.right}>
              <div className={s.percent}>
                <Progress
                  shape="line"
                  percent={Number(
                    (item.number /
                      Number(type == "expense" ? totalExpense : totalIncome)) *
                      100
                  ).toFixed(2)}
                  theme="success"
                />
              </div>
            </div>
          </div>
        ))}
      </div>

      <PopupDate ref={monthRef} mode="month" onSelect={selectMonth} />
    </div>
  );
};

export default Data;
